$(document).ready(function() {
//    $(".vote_item").mouseover(function () {
//        $(this).find(".vote_button").show();
//    });
//    $(".vote_item").mouseout(function () {
//        $(this).find(".vote_button").hide();
//    });
    
    /*=============green hovers=========================*/
    $("#main_blocks a").mouseover(function () {
        $(this).find(".main_block_title").addClass('main_block_title_active');
    });
    $("#main_blocks a").mouseout(function () {
        $(this).find(".main_block_title").removeClass('main_block_title_active');
    });
    
    $("#custom_order").mouseover(function () {
        $(this).find(".custom_block_title").addClass('custom_block_title_active');
    });
    $("#custom_order").mouseout(function () {
        $(this).find(".custom_block_title").removeClass('custom_block_title_active');
    });
    /*=============green hovers end=====================*/
    
    /*Contact AJAX */
    $('.contact_form input[type=submit]').click(function(e){
        e.preventDefault();
        var email = $('.contact_form input[name=email]').val();
        var message = $('.contact_form textarea').val();
        var subject = $('.contact_form option:selected').text();
        
        
        $.ajax({
            type    : 'POST',
            url     : '/contact/contact/',
            dataType: 'json',
            data    : {email:email,subject:subject,message:message},
            success : function(msg) {
                $('.contact_form input[name=email]').val('');
                $('.contact_form textarea').val('');
                alert('e-Mail sent');
                window.location.href='/';
            },
            error   : function(msg){
                alert('Information is not valid.Please try again');
            }
        });
    })
    
/*Cart AJAX*/


/*Cart close*/
$('.cart_close,.continue_shopping').live('click',function(){
    $.fancybox.close();
});

/*Cart checkout*/
$('.proceed_checkout').live('click',function(){
    window.location.href = "/commerce/checkout/";
});
  



/*CART AJAX*/
////////////////////////////
////////////////////////////

$(function() {
	var load = new Image();
	load.src = '/images/loader.gif';
        
        $('.item_add').live('click',function() {
                    
                    var id = $(this).children('a').attr('id'),
                        color = $('.active_color').attr('title'),
                        size = $('.active_size').attr('title'),
                        price = $('.item_info_price').text(),
                        name = $('.item_info_name').text(),
                        content = $('#content')
                        loader(content.parent(), 'show');
                    
                    $.ajax({
                            type	: 'POST',
                            url: '/cart/add/set/' + id + '/',
                            dataType: 'json',
                            data	: {'color': color, 'size' : size, 'id' : id , 'price' : price, 'name' : name},
                            success: function(data) {
                                loader(content.parent(), 'hide');
                                    if (data.success) {
                                            
//                                            $.fancybox.close();
                                            $('.show_cart').show(100);
                                            $('#incart').text(data.success);
                                    } else {
                                            alert(data.errors);
                                            $('#incart').text(data.eRquantity);
                                    }
                            },
                            error: function() {
                                    $('#response').html('Something went wrong. Refresh page and try again.');
                            }
                    });
                    return false;
            });
        
        $(".cartlink,#incart").fancybox({
            fitToView       : false,
            width           : 950,
            height          : 600,
            href            : '#cartContainer',
            autoSize        : false,
            closeClick      : false,
            openEffect      : 'elastic',
            closeEffect     : 'elastic',
            closeBtn        : false,
            padding         : 0,
            beforeLoad      : function(){
                                updateCart();
            }

            });
        
           

	$('#flushCart').click(function(e) {

		$('.show_cart').hide(200);
		$.fancybox.close();
		return e.preventDefault();
   	});
        
        
        $('#cont_shop').live('click', function(e)
        {
		$.fancybox.close();
		return e.preventDefault();
        })

    
    $('.cart_item_remove_btn').live('click', function(e) {
		e.preventDefault();
                var count = $('#incart').text();
                var quant = $(this).parent().parent().find('.cart_item_quantity input').val();
//                $('#incart').text(count-quant);
                var removeId = $(this).attr('id');
                var color = $(this).parent().parent().find('.item_span_color').text(),
                    size  = $(this).parent().parent().find('.item_span_size').text(),
                    id    = $(this).parent().parent().parent().attr('data-id');
                    var test =$(this).parent().parent().parent();
                    content = $('#cartContainer')
                    loader(content.parent(), 'show');
                    
                    
                $.ajax({
                        type    :   'POST',
                        url     :   '/cart/cartDeleteItem/',
                        dataType :  'json',
                        data    :   {'id' : removeId},
                        success :   function(data)
                                    {
                                        $('#incart').text(data.quant);
                                        test.slideUp();
                                        var element = $('.cart_items_wrapper').jScrollPane({/* ...settings... */});
                                        var api = element.data('jsp');
                                        api.reinitialise();
                                        
                                        $('.cart_total span').text(data.total);
                                        
                                    },
                        error   :   function(msg)
                                    {alert('not deleted');},
                        complete :  function(){
                                    loader(content.parent(), 'hide');
                        }
                
                
                });
   	});
    
        
        $('.cart_item_quantity').live('keypress',function(e){
              $(this).find('img').css('display','inline');
        })
        
        $('.cart_item_quantity img').live('click',function(e){
            var quantity = $(this).parent().find('input').attr('value'),
                id = $(this).parent().parent().find('.cart_item_remove span').attr('id');
                
                content = $('#cartContainer');
                loader(content.parent(), 'show');
                
                $.ajax({
                        type    :   'POST',
                        url     :   '/cart/quantity/',
                        dataType :  'json',
                        data    :   {'quantity' : quantity,'id' :id},
                        success :   function(data)
                                    {
                                        updateCartNew();
                                    },
                         
                        error   :   function(msg)
                                    {alert('not changed');}
                                    ,
                        complete :  function(){
//                                    loader(content.parent(), 'hide');
                        }
                
                    });
                    $(this).hide();
        })
        
        /*Bonus scripts*/
        $('.use_bonus').live('keypress',function(e){
              $(this).find('img').css('display','inline');
        })
        
        
        
        $('.use_bonus img').live('click',function(e){
                var bonus_new = $(this).parent().find('input').val(),
                    account_bonus = $(this).parent().parent().find('.bonus_amount span').text();
                 
                self = $(this);
                content = $('#content');
                loader(content.parent(), 'show');
                
                    $.ajax({
                        type    :   'POST',
                        url     :   '/commerce/takebonus/',
                        dataType :  'json',
                        data    :   {'bonus_new' : bonus_new},
                        success :   function(data)
                                    {
                                      if(data.success){
                                          self.parent().parent().find('.bonus_amount span').text(data.success.acc_amount_new);
                                          self.parent().find('input').val(data.success.bonus_new);
                                      }
                                        else{
                                            alert(data.error.message);
                                            self.parent().find('input').val('');
                                            self.parent().parent().find('.bonus_amount span').text(data.error.amount);
                                        }
                                    },
                         
                        error   :   function(msg)
                                    {alert('not changed');}
                                    ,
                        complete :  function(){
                                    loader(content.parent(), 'hide');
                        }
                
                    });
                    $(this).hide();
                    
                  
                
        })
        /*Bonus end*/

        function updateCart()
        {
                $('#cartContainer').empty();

                $.ajax({
                        type: 'POST',
                        url: '/cart/cart/',
                        success: function(msg) {
                            
                                var cartContent = msg;
                                $('#cartContainer').html(cartContent).hide().fadeIn(300);
                                
                                }
                });
        }
        function updateCartNew()
        {
                content = $('#cartContainer');
                
                $.ajax({
                        type: 'POST',
                        url: '/cart/cartUpdate/',
                        dataType: 'json',
                        success: function(data) {
                                if(data.quant >99) {
                                    var quantity = '99+';
                                }
                                else{
                                    var quantity = data.quant;
                                }
                                $('#incart').text(quantity);
                                $('.cart_item').each(function(){
                                    var subtotal = $(this).find('.cart_item_subtotal');
                                    var id = $(this).attr('data-id');
                                    var color = $(this).find('.item_span_color').text();
                                    var size = $(this).find('.item_span_size').text();
                                    var cartTotal = $('.cart_total span');
                                    $.each(data.items, function(key,value) {
                                            if(id == value['id'] && color == value['settings']['color'] && size == value['settings']['size'])
                                            {
                                                subtotal.text(value['price']*value['quantity']);
                                                cartTotal.text(data.total);
                                            }          
                                    });
                                    
                                })
                                
                                },
                        complete:   function(){
                            loader(content.parent(), 'hide');
                        }
                });
        }
        
      function loader($this, action) {
	var loader = new Image();
	loader.src = '/images/loader.gif';

	switch(action) {
		case 'show':
			if($this.children('.loader').length == 0) {
				var wBlock = $(window).width();
				var hBlock = $(window).height();
				var c = '<div class="loader" style="position: fixed; display: none; opacity: 0.8"></div>';
				$this.append(c);
				var newLoader = new Image();
				newLoader.src = loader.src;

				$this.children('.loader').append(newLoader);
				$this.children('.loader').css({
					'top': (hBlock-newLoader.height > 0) ? (hBlock-newLoader.height)/2 : 0,
					'left': (wBlock-newLoader.width > 0) ? (wBlock-newLoader.width)/2 : 0
				}).fadeTo(100, 1);
			}
			break;
		case 'hide':
			$this.children('.loader').stop().fadeOut(100, function() {
				$(this).remove();
			});
			break;
	}
};  
        
});

///////////////////////////   
///////////////////////////   
/*CART AJAX end*/  

/*shipping list scripts*/
$('.shipping-list li').hover(
function(){
    $(this).find('.ship-pane').slideDown();
},
function(){
    $(this).find('.ship-pane').slideUp();
});
/*shipping list scripts end*/


/*voting*/
$('.vote_button').live('click',function(){
    var id = $(this).parent().find('img').data('id');
    var self = $(this);
    
    $.ajax({
                        type: 'POST',
                        url: '/vote/index/',
                        dataType: 'json',
                        data	: {'id' : id},
                        success: function(data) {
                            if(data.success)
                                {

                                    self.parent().find('.vote_result').text(data.result + ' votes ').show();
//                                    alert(data.success);
                                    self.hide();

                                    self.parent().find('.vote_result span').text(data.result);
                                    alert(data.success);

                                }
                            else
                            {
                                if(data.error.redirect)
                                    {
                                        alert(data.error.redirect);
                                        window.location.href='/signin/';
                                        
                                    }
                                    else
                                    alert(data.error);
                            }
                                 
                                }
                });
    
})
/*voting end*/

/*Add favourite size*/
$('.size_chart_img table td').live('click',function(){

    var favSize = $(this).text();
    $.ajax({
        type    :   'POST',
        url     :   '/account/favourite/',
        dataType :  'json',
        data    :   {'size' : favSize},
        success :   function(data)
        {
            if(data.success){
                alert(data.success)
            }
            else{
                alert(data.error);
            }

        },
        error   :   function(data){
            alert('You are not logged in!');
            window.location.href = '/signin/';
        },
        complete :  function(){

        }


    });
/*Add favourite size end*/
});

});